package com.eims.sls_app.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.eims.sls_app.dataaccess.LotteryContent;
import com.eims.sls_app.dataaccess.Schemes;
import com.eims.sls_app.dataaccess.SelectedNumbers;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.utils.NumberTools;
import com.eims.sls_app.utils.RequestUtil;
import com.eims.sls_app.view.MyToast;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JxccsBetActivity extends BaseBetActivity {
	private static String TAG = "JxccsBetActivity";
	private Context context = JxccsBetActivity.this;

	private DecimalFormat format = new DecimalFormat("#####0.00");
	private int typeID;
	private String typeName;
	private int countForRandom;
	private Schemes scheme;

	@Override
	protected List<SelectedNumbers> parseParamsToList(Intent intent) {
		Bundle bundle = intent.getBundleExtra("bundle");
		List<SelectedNumbers> list = new ArrayList<SelectedNumbers>();
		if (bundle != null) {
			typeID = bundle.getInt("playType");
			typeName = bundle.getString("playTypeName");
			countForRandom = bundle.getInt("count");
			String one = notNullOr0(bundle.getString("one"));
			String two = notNullOr0(bundle.getString("two"));
			String three = notNullOr0(bundle.getString("three"));
			String four = notNullOr0(bundle.getString("four"));
			String five = notNullOr0(bundle.getString("five"));
			list.add(parseParamsToObj(typeID, typeName, countForRandom, one,
					two, three, four, five));
			System.out.println("++++++++++++++++countForRandom++++"
					+ countForRandom);
			if (App.list_numbers != null) {
				for (SelectedNumbers select : App.list_numbers) {
					list.add(select);
				}
				App.list_numbers.clear();
				App.totalCount = 0;
			}
		}
		if (intent.getBooleanExtra("isContinue", false)) {
			typeID = intent.getIntExtra("playType", 0);
			typeName = intent.getStringExtra("playTypeName");
//			scheme = (Schemes) intent.getSerializableExtra("scheme");
			scheme= App.scheme;
			if (scheme != null) {
				List<LotteryContent> buyContent = scheme.getBuyContent();
				Log.i("======", buyContent.size() + "----------------");// TODO
																		// 这里的size是1
				countForRandom = Integer
						.parseInt(buyContent.get(0).getSumNum());
				for (LotteryContent con : buyContent) {
					SelectedNumbers select = new SelectedNumbers();
					select.setPlayType(typeID);
					select.setPlayTypeName(typeName);
					select.setCount(Long.parseLong(con.getSumNum()));
					select.setMoney(Long.parseLong(con.getSumNum()) * 2);
					select.setLotteryNumber(con.getLotteryNumber());
					list.add(select);
				}
			}
		}

		if (App.list_numbers != null) {
			for (SelectedNumbers select : App.list_numbers) {
				list.add(select);
			}
			App.list_numbers.clear();
		}
		return list;
	}

	@Override
	protected void backNewIntent(Intent intent) {
		// do nothing
	}

	@Override
	protected String currentLotteryName() {
		return "江西时时彩";
	}

	@Override
	protected void startJoint() {
		int total = getCount() * bei * 2;
		App.bei = bei;
		App.list_numbers = dropLastChar(listSchemes);
		Intent intent = new Intent(this, JoinActivity.class);
		intent.putExtra("totalMoney", total + "");
		this.startActivity(intent);
	}

	@Override
	protected void startPay() {
		long count = (long) getCount();
		final long totalMoney = count * bei * qi * 2;
		App.list_numbers = dropLastChar(listSchemes);
		App.bei = bei;
		App.qi = qi;
		RequestUtil requestUtil = new RequestUtil(this, false, 0, true,
				"正在支付...") {
			@Override
			public void responseCallback(JSONObject object) {
				if (RequestUtil.DEBUG)
					Log.i(TAG, "江西时时彩投注支付结果" + object);
				String error = object.optString("error");
				String resultMsg = object.optString("msg");
				if ("0".equals(error)) {
					App.user.setBalance(object.optDouble("balance"));
					App.user.setFreeze(object.optDouble("freeze"));
					App.schemeId = object.optInt("schemeids");
					App.lottery.setChaseTaskID(object
							.optInt("chasetaskids"));
					App.list_numbers.clear();
					App.totalCount = 0;
					String SucJinECost = format.format(object
							.optDouble("currentMoeny"));
					String SucCaiJinCost = format.format(object
							.optDouble("currentHandsel"));
					String SuccMoney = format.format(object
							.optDouble("handselMoney"));
					Intent intent = new Intent(getApplicationContext(),
							PaySuccessActivity.class);

					intent.putExtra("JXSSCType", typeID);

					intent.putExtra("currentMoeny", SucJinECost);
					intent.putExtra("currentHandsel", SucCaiJinCost);
					intent.putExtra("handselMoney", SuccMoney);
					intent.putExtra("paymoney", totalMoney);
					startActivity(intent);
				} else if (error.equals(App.ERROR_MONEY + "")) {
					LotteryUtils.showMoneyLess(context, totalMoney);
				} else if (error.equals("-500")) {
					MyToast.getToast(context, "连接超时").show();
				} else {
					Toast.makeText(context, resultMsg + "", Toast.LENGTH_SHORT)
							.show();
				}
			}

			@Override
			public void responseError(VolleyError error) {
				MyToast.getToast(context, "抱歉，支付出现未知错误..").show();
				if (RequestUtil.DEBUG)
					Log.e(TAG, "投注支付报错" + error.getMessage());
			}
		};
		requestUtil.commitBetting(count, totalMoney, isStopChase);
	}

	@Override
	protected void continueSelect() {
		Intent intent = new Intent(this, Select_JXSSCActivity.class);
		startActivity(intent);
	}

	@Override
	protected void automaticSelect() {
		// TODO 随机只出当前最近的玩法
		int[] cantRandom = new int[] { 6119, 6127, 6128, 6122, 6110, 6118, 6117 };
		for (int i = 0; i < cantRandom.length; i++) {
			if (typeID == cantRandom[i]) {
				MyToast.getToast(
						JxccsBetActivity.this,
						LotteryUtils.transPlayName(typeID + "", "1")
								+ " 暂不支持机选！").show();
				return;
			}
		}
		int count = 1;
		Map<String, String> stringMap = getRandomMap(typeID);
		String one = notNullOr0(stringMap.get("one"));
		String two = notNullOr0(stringMap.get("two"));
		String three = notNullOr0(stringMap.get("three"));
		String four = notNullOr0(stringMap.get("four"));
		String five = notNullOr0(stringMap.get("five"));
		SelectedNumbers numbers = parseParamsToObj(typeID, typeName, count,
				one, two, three, four, five);
		if (numbers != null) {
			addOneSelect(numbers);
		}

		// Map<String,String> map= LotteryHelp.getRandomType();
		// int typeId=Integer.valueOf(map.get("typeId"));
		// String typeName=map.get("typeName");
		// int count=Integer.valueOf(map.get("count"));
		// Map<String,String> stringMap=getRandomMap(typeId);
		// String one=notNullOr0(stringMap.get("one"));
		// String two=notNullOr0(stringMap.get("two"));
		// String three=notNullOr0(stringMap.get("three"));
		// String four=notNullOr0(stringMap.get("four"));
		// String five=notNullOr0(stringMap.get("five"));
		// SelectedNumbers
		// numbers=parseParamsToObj(typeId,typeName,count,one,two,three,four,five);
		// if (numbers!=null){
		// addOneSelect(numbers);
		// }
	}

	@Override
	public void automaticSelect(View view) {
		automaticSelect();
		Log.i("江西时时彩机选", "触发点击事件");
	}

	@Override
	protected void clickListItem(int position) {
		Intent intent = new Intent(this, Select_JXSSCActivity.class);
		SelectedNumbers numbers = listSchemes.get(position);
		int TypeId = numbers.getPlayType();
		Bundle bundle = new Bundle();
		bundle.putInt("playType", TypeId);
		bundle.putString("playTypeName", numbers.getPlayTypeName());
		bundle.putInt("count", (int) numbers.getCount());
		ArrayList<String> oneList = new ArrayList<String>();
		ArrayList<String> twoList = new ArrayList<String>();
		ArrayList<String> threeList = new ArrayList<String>();
		ArrayList<String> fourList = new ArrayList<String>();
		ArrayList<String> fiveList = new ArrayList<String>();
		String shownum = numbers.getLotteryNumber();
		if (shownum == null)
			return;
		switch (TypeId) {
		// 个位
		case 61031:// ----(01)
			String[][] s = regex(shownum);
			Collections.addAll(fiveList, s[0]);
			oneList = null;
			twoList = null;
			threeList = null;
			fourList = null;
			break;
		case 6106:
		case 6112:
		case 6111:
		case 6116:
		case 6129:
		case 6123:
			// 0 1 2
			String[] str = shownum.trim().split(" ");
			Collections.addAll(fiveList, str);
			oneList = null;
			twoList = null;
			threeList = null;
			fourList = null;
			break;
		case 6119:
		case 6127:
		case 6128:
		case 6122:
			// 和值
		case 6110:
		case 6118:
		case 6117:
			// 0,1
			String[] HEZHI = shownum.trim().split(",");
			Collections.addAll(fiveList, HEZHI);
			oneList = null;
			twoList = null;
			threeList = null;
			fourList = null;
			break;
		// 十个位
		case 61032:
			// ---(01)(01)
			String[][] ss = regex(shownum);
			for (int i = 0; i < ss.length; i++) {
				if (i == 0) {
					Collections.addAll(fourList, ss[i]);
				}
				if (i == 1) {
					Collections.addAll(fiveList, ss[i]);
				}
			}
			oneList = null;
			twoList = null;
			threeList = null;
			break;
		// 大小单双
		case 6104:
			// 大大
			char[] chars1 = shownum.trim().toCharArray();
			fourList.add(String.valueOf(chars1[0]));
			fiveList.add(String.valueOf(chars1[1]));
			oneList = null;
			twoList = null;
			threeList = null;
			break;
		case 6130:
		case 6131:
		case 6132:
		case 6124:
		case 6126:
		case 6120:
		case 6121:
			// 0 1,2 3
			String[] ss1 = shownum.trim().split(",");
			Collections.addAll(fourList, ss1[0].split(" "));
			Collections.addAll(fiveList, ss1[1].split(" "));
			oneList = null;
			twoList = null;
			threeList = null;
			break;
		// 百十个

		case 61033:
			// --(01)(01)(01)
			String[][] ss2 = regex(shownum);
			for (int i = 0; i < ss2.length; i++) {
				if (i == 0) {
					Collections.addAll(threeList, ss2[i]);
				}
				if (i == 1) {
					Collections.addAll(fourList, ss2[i]);
				}
				if (i == 2) {
					Collections.addAll(fiveList, ss2[i]);
				}
			}
			oneList = null;
			twoList = null;
			break;
		case 6125:
			// 0 1,2 3,4 5
			String[] ss3 = shownum.trim().split(",");
			Collections.addAll(threeList, ss3[0].split(" "));
			Collections.addAll(fourList, ss3[1].split(" "));
			Collections.addAll(fiveList, ss3[2].split(" "));
			oneList = null;
			twoList = null;
			break;
		case 6133:
			// 大小 12 23
			String[] ss4 = shownum.trim().split(" ");
			for (int i = 0; i < ss4.length; i++) {
				char[] c = ss4[i].trim().toCharArray();
				String[] sc = new String[c.length];
				for (int j = 0; j < c.length; j++) {
					sc[j] = String.valueOf(c[j]);
				}
				if (i == 0) {
					Collections.addAll(threeList, sc);
				}
				if (i == 1) {
					Collections.addAll(fourList, sc);
				}
				if (i == 2) {
					Collections.addAll(fiveList, sc);
				}
			}
			oneList = null;
			twoList = null;
			break;
		// 千百十个
		case 61034:
			// -(01)(01)(01)(0)
			String[][] ss5 = regex(shownum);
			for (int i = 0; i < ss5.length; i++) {
				if (i == 0) {
					Collections.addAll(twoList, ss5[i]);
				}
				if (i == 1) {
					Collections.addAll(threeList, ss5[i]);
				}
				if (i == 2) {
					Collections.addAll(fourList, ss5[i]);
				}
				if (i == 3) {
					Collections.addAll(fiveList, ss5[i]);
				}
			}
			oneList = null;
			break;
		// 万千百十个
		case 6113:
		case 6114:
		case 6115:
		case 6105:
		case 61035:
			// (0)(01)(01)(01)(0)
			String[][] ss6 = regex(shownum.replaceAll("-", "()"));
			for (int i = 0; i < ss6.length; i++) {
				if (i == 0) {
					Collections.addAll(oneList, ss6[i]);
				}
				if (i == 1) {
					Collections.addAll(twoList, ss6[i]);
				}
				if (i == 2) {
					Collections.addAll(threeList, ss6[i]);
				}
				if (i == 3) {
					Collections.addAll(fourList, ss6[i]);
				}
				if (i == 4) {
					Collections.addAll(fiveList, ss6[i]);
				}
			}
			break;
		}
		bundle.putStringArrayList("one", oneList);
		bundle.putStringArrayList("two", twoList);
		bundle.putStringArrayList("three", threeList);
		bundle.putStringArrayList("four", fourList);
		bundle.putStringArrayList("five", fiveList);
		bundle.putString("position", position + "");
		intent.putExtra("bundle", bundle);
		startActivity(intent);

	}

	/**
	 * 将参数转换成对象
	 * 
	 * @param TypeID
	 *            玩法id
	 * @param TypeName
	 *            玩法名称
	 * @param count
	 *            注数
	 * @param data
	 *            号码详情
	 * @return SelectedNumbers
	 */
	private SelectedNumbers parseParamsToObj(int TypeID, String TypeName,
                                             int count, String... data) {
		SelectedNumbers numbers = new SelectedNumbers();
		numbers.setPlayType(TypeID);
		numbers.setPlayTypeName(TypeName);
		numbers.setCount(count);
		numbers.setMoney(count * 2);

		String one = data[0];
		String two = data[1];
		String three = data[2];
		String four = data[3];
		String five = data[4];

		switch (TypeID) {
		// 个位
		case 61031:// ----(01)
			numbers.setLotteryNumber("----(" + five.replace(",", "") + ")");
			break;
		case 6106:
		case 6112:
		case 6111:
		case 6116:
		case 6129:
		case 6123:
			// 0 1 2
			numbers.setLotteryNumber(five.replace(",", " "));
			break;
		case 6119:
		case 6127:
		case 6128:
		case 6122:
			// 和值
		case 6110: // TODO 这里改成不支持机选
		case 6118:
		case 6117:
			// 0,1
			numbers.setLotteryNumber(five);
			break;
		// 十个位
		case 61032:
			// ---(01)(01)
			numbers.setLotteryNumber("---(" + four.replace(",", "") + ")("
					+ five.replace(",", "") + ")");
			break;
		// 大小单双
		case 6104:
			// 大大
			numbers.setLotteryNumber(four.replace(",", "")
					+ five.replace(",", ""));
			break;
		case 6130:
		case 6131:
		case 6132:
		case 6124:
		case 6126:
		case 6120:
		case 6121:
			// 0 1,2 3
			numbers.setLotteryNumber(four.replace(",", " ") + ","
					+ five.replace(",", " "));
			break;
		// 百十个

		case 61033:
			// --(01)(01)(01)
			numbers.setLotteryNumber("--(" + three.replace(",", "") + ")("
					+ four.replace(",", "") + ")(" + five.replace(",", "")
					+ ")");
			break;
		case 6125:
			// 0 1,2 3,4 5
			numbers.setLotteryNumber(three.replace(",", " ") + ","
					+ four.replace(",", " ") + "," + five.replace(",", " "));
			break;
		case 6133:
			// 大小 12 23
			numbers.setLotteryNumber(three.replace(",", "") + " "
					+ four.replace(",", "") + " " + five.replace(",", ""));
			break;
		// 千百十个
		case 61034:
			// -(01)(01)(01)(0)
			numbers.setLotteryNumber("-(" + two.replace(",", "") + ")("
					+ three.replace(",", "") + ")(" + four.replace(",", "")
					+ ")(" + five.replace(",", "") + ")");
			break;
		// 万千百十个
		case 6113:
		case 6114:
		case 6115:
		case 6105:
		case 61035:
			// (0)(01)(01)(01)(0)
			if (!one.equals("-")) {
				one = "(" + one.replace(",", "") + ")";
			}
			if (!two.equals("-")) {
				two = "(" + two.replace(",", "") + ")";
			}
			if (!three.equals("-")) {
				three = "(" + three.replace(",", "") + ")";
			}
			if (!four.equals("-")) {
				four = "(" + four.replace(",", "") + ")";
			}
			if (!five.equals("-")) {
				five = "(" + five.replace(",", "") + ")";
			}
			numbers.setLotteryNumber(one + two + three + four + five);
			break;
		}
		return numbers;
	}

	private String notNullOr0(String s) {
		return s == null || s.length() == 0 ? "-" : s;
	}

	/**
	 * 将61031,61032,61033,61034,61035转换成正常的6103进行投注
	 */
	private List<SelectedNumbers> dropLastChar(List<SelectedNumbers> list) {
		List<SelectedNumbers> temp = new ArrayList<SelectedNumbers>();
		for (SelectedNumbers numbers : list) {
			if (numbers.getPlayType() / 10000 == 6) {
				numbers.setPlayType(numbers.getPlayType() / 10);
			}
			temp.add(numbers);
		}
		return temp;
	}

	/**
	 * 匹配括号里面的内容
	 */
	private String[][] regex(String str) {
		String regex = "\\(([^)]*)\\)";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		String[][] mix = new String[5][];
		int i = 0;
		while (matcher.find()) {
			char[] c = matcher.group(1).toCharArray();
			String[] n = new String[c.length];
			for (int j = 0; j < c.length; j++) {
				n[j] = String.valueOf(c[j]);
			}
			mix[i++] = n;
		}
		return mix;
	}

	private Map<String, String> getRandomMap(int typeID) {
		Map<String, String> map = new HashMap<String, String>();
		String[] dxds = { "大", "小", "单", "双" };
		String[] dx = { "大", "小" };
		if (typeID == 6104) { // 大小单双
			int index = (int) (Math.random() * 4);
			int index1 = (int) (Math.random() * 4);
			map.put("four", dxds[index]);
			map.put("five", dxds[index1]);
		} else if (typeID == 6133) { // 趣味二星
			int index = (int) (Math.random() * 2);
			map.put("three", dx[index]);
			map.put("four", setOneRandomSet(1, 9));
			map.put("five", setOneRandomSet(1, 9));
		} else if (typeID == 61031 || typeID == 6127 || typeID == 6128
				|| typeID == 6122) {
			map.put("five", setOneRandomSet(1, 9));
		} else if (typeID == 6106 || typeID == 6111) {
			map.put("five", setOneRandomSet(2, 9));
		} else if (typeID == 6112 || typeID == 6116) {
			map.put("five", setOneRandomSet(3, 9));
		} else if (typeID == 6129) {
			map.put("five", setOneRandomSet(4, 9));
		} else if (typeID == 6123) {
			map.put("five", setOneRandomSet(5, 9));
		} else if (typeID == 61032) {
			map.put("four", setOneRandomSet(1, 9));
			map.put("five", setOneRandomSet(1, 9));
		} else if (typeID == 6130 || typeID == 6126) {
			String temp = setOneRandomSet(1, 9);
			String temp1 = setOneRandomSet(temp, 2, 9);
			map.put("four", temp);
			map.put("five", temp1);
		} else if (typeID == 6131 || typeID == 6132 || typeID == 6120
				|| typeID == 6121) {
			String temp = setOneRandomSet(1, 9);
			String temp1 = setOneRandomSet(temp, 1, 9);
			map.put("four", temp);
			map.put("five", temp1);
		} else if (typeID == 6124) {
			String temp = setOneRandomSet(1, 9);
			String temp1 = setOneRandomSet(temp, 3, 9);
			map.put("four", temp);
			map.put("five", temp1);
		} else if (typeID == 61033) {
			map.put("three", setOneRandomSet(1, 9));
			map.put("four", setOneRandomSet(1, 9));
			map.put("five", setOneRandomSet(1, 9));
		} else if (typeID == 6125) {
			String temp = setOneRandomSet(1, 9);
			String temp1 = setOneRandomSet(temp, 1, 9);
			String temp2 = setOneRandomSet(temp + "," + temp1, 1, 9);
			map.put("three", temp);
			map.put("four", temp1);
			map.put("five", temp2);
		} else if (typeID == 61034) {
			map.put("two", setOneRandomSet(1, 9));
			map.put("three", setOneRandomSet(1, 9));
			map.put("four", setOneRandomSet(1, 9));
			map.put("five", setOneRandomSet(1, 9));
		} else if (typeID == 61035 || typeID == 6105) {
			map.put("one", setOneRandomSet(1, 9));
			map.put("two", setOneRandomSet(1, 9));
			map.put("three", setOneRandomSet(1, 9));
			map.put("four", setOneRandomSet(1, 9));
			map.put("five", setOneRandomSet(1, 9));
		} else if (typeID == 6113) {
			String[] po = new String[] { "one", "two", "three", "four", "five" };
			map.put(po[NumberTools.getRandomNumInt(1, 4).get(0)],
					setOneRandomSet(1, 9));
		} else if (typeID == 6114) {
			String[] po = new String[] { "one", "two", "three", "four", "five" };
			List<Integer> listpo = NumberTools.getRandomNumInt(2, 4);
			map.put(po[listpo.get(0)], setOneRandomSet(1, 9));
			map.put(po[listpo.get(1)], setOneRandomSet(1, 9));
		} else if (typeID == 6115) {
			String[] po = new String[] { "one", "two", "three", "four", "five" };
			List<Integer> listpo = NumberTools.getRandomNumInt(3, 4);
			map.put(po[listpo.get(0)], setOneRandomSet(1, 9));
			map.put(po[listpo.get(1)], setOneRandomSet(1, 9));
			map.put(po[listpo.get(2)], setOneRandomSet(1, 9));
		}
		return map;
	}

	private String setOneRandomSet(int count, int max) {
		StringBuilder builder = new StringBuilder();
		List<String> list = NumberTools.getRandomNum(count, max);
		for (String one : list) {
			builder.append(one).append(",");
		}
		return builder.substring(0, builder.length() - 1);
	}

	private String setOneRandomSet(String except, int count, int max) {
		StringBuilder builder = new StringBuilder();
		List<String> listexcept = new ArrayList<String>();
		String[] ex = except.split(",");
		Collections.addAll(listexcept, ex);
		List<String> list = NumberTools.getRandomNum(listexcept, count, max);
		for (String one : list) {
			builder.append(one).append(",");
		}
		return builder.substring(0, builder.length() - 1);
	}
}
